<?php

/**
 * Description of auto_restart_server
 *
 * @author Administrator
 */
class auto_restart_server
{

	private static $is_change = false;

	private static function init()
	{
		$GLOBALS['code_mtime'] = [];
	}

	public static function run()
	{
		self::init();

		$base = event_base_new();
		$tv_value = 1000000 * 0.1; //秒

		$ev_timer = event_timer_new();
		event_timer_set($ev_timer, 'self::event_timer_fun', array($ev_timer, $tv_value));
		event_base_set($ev_timer, $base);
		event_timer_add($ev_timer, $tv_value);

		$ev_timer_2 = event_timer_new();
		event_timer_set($ev_timer_2, 'self::event_timer_fun2', array($ev_timer_2, 1000000 * 1));
		event_base_set($ev_timer_2, $base);
		event_timer_add($ev_timer_2, 1000000 * 1);

		event_base_loop($base);
	}

	/**
	 * 定时器事件
	 */
	private static function event_timer_fun($socket, $flag, $arr)
	{
		self::check_code_ischange(__DIR__);
		if (self::$is_change)
			self::restart();
		event_timer_add($arr[0], $arr[1]);
	}

	private static function check_code_ischange($dir)
	{
		$handle = opendir($dir);
		if (!$handle)
			die('opendir ' . $dir . ' error');

		while (( $file = readdir($handle) ) !== false) {
			if ($file == '.' || $file == '..')
				continue;
			$cur_path = $dir . DIRECTORY_SEPARATOR . $file;

			if (is_dir($cur_path)) {
				self::check_code_ischange($cur_path);
				continue;
			}

			$time = filectime($cur_path);
			$key = str_replace(DIRECTORY_SEPARATOR, '__', $cur_path);
			if (!isset($GLOBALS['code_mtime'][$key])) {
				$GLOBALS['code_mtime'][$key] = $time;
				continue;
			}

			if ($GLOBALS['code_mtime'][$key] != $time) {
				echo "[" . date('Y-m-d H:i:s') . "][服务需要重启] file $cur_path is change \n";
				$GLOBALS['code_mtime'][$key] = $time;
				self::$is_change = true;
				break;
			}
		}

		closedir($handle);
	}

	/**
	 * 重启服务
	 */
	private static function restart()
	{
		$shell = 'cd ' . __DIR__ . ';php start.php restart';
		pclose(popen($shell, 'r'));
		self::$is_change = false;
	}

	private static function event_timer_fun2($socket, $flag, $arr)
	{
		echo "[" . date('Y-m-d H:i:s') . "]\n";
		event_timer_add($arr[0], $arr[1]);
	}

}

auto_restart_server::run();
